package com.smartTerminal.user.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smartTerminal.user.entity.User;
import com.smartTerminal.user.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService ;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 注册
	 * @method	register
	 * @author	Xia.Zhuming
	 * @data	2018年1月9日
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/register",method={RequestMethod.GET,RequestMethod.POST})
	public String register(HttpServletRequest request, User user){
		String service = user.getService();
		try {
			userService.register(user);
		} catch (Exception e) {
			request.setAttribute("tips", e.getMessage());
			return "user/error";
		}
		//注册成功自动登录
		try {
			userService.login(user, request.getSession());
		} catch (Exception e) {
			request.setAttribute("tips", e.getMessage());
			return "user/error";
		}
		//注册和登录成功自动跳转相关页面
		request.setAttribute("user", user);
		return service;
	} 
	
	/**
	 * 登录
	 * @method	login
	 * @author	Xia.Zhuming
	 * @data	2018年1月9日
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/login",method={RequestMethod.GET,RequestMethod.POST})
	public String login(HttpServletRequest request, User user){
		String service = user.getService();
		try {
			userService.login(user, request.getSession());
		} catch (Exception e) {
			String code = e.getMessage();
			if("-1".equals(code)){
				request.setAttribute("tips", "身份信息识别有误,请重新识别");
				return "user/error";
			}
			request.setAttribute("user", user);
			return "user/register";
		}
		request.setAttribute("user", user);
		return service;
	}
	
	/**
	 * 跳转至扫描二维码页面
	 * @method	scanQRCode
	 * @author	Xia.Zhuming
	 * @data	2018年1月15日
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/scanQRCode",method={RequestMethod.GET,RequestMethod.POST})
	public String scanQRCode(HttpServletRequest request){
		return "user/scanQRCode";
	}
	
	/**
	 * 退出
	 * @method	loginOut
	 * @author	Xia.Zhuming
	 * @data	2018年1月9日
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/loginOut",method={RequestMethod.GET,RequestMethod.POST})
	public String loginOut(HttpServletRequest request) {
		try {
			userService.loginOut(request.getSession());
		} catch (Exception e) {
			request.setAttribute("tips", e.getMessage());
			return "user/error";
		}
		//退出登录跳转至首页
		return "redirect:index.jsp";
	}
}
